// index.js
import config from "../../utils/config";

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const app = getApp()
import _ from './../../utils/lodash.js';
import util from './../../utils/util.js';
const find = _.find;

function isNumericStart(str) {
  return /^\d/.test(str);
}

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

Page({
  data: {
    // devices: [{MAC: "",
    // RSSI: -69,
    // advertisServiceUUIDs: [],
    // connectable: true,
    // deviceId: "FB:37:E1:0B:69:22",
    // localName: "76895768D",
    // name: "76895768D"}],
    devices:[],
    loading: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  openBluetoothAdapter() {
    //util.toastError('请先打开蓝牙');
    console.log('openBluetoothAdapter')
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        console.log('openBluetoothAdapter fail', res)
        util.toastError('请先打开蓝牙'+res.errCode);
        if (res.errCode === 10001) {
          console.log('请先打开蓝牙1') //当蓝牙开关未开启或手机不支持蓝牙时，会返回错误 (errCode=10001)。
          // util.toastError('10001');
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    // if (this._discoveryStarted) {
    //   return
    // }
    // this._discoveryStarted = true
    this.setData({
      loading: true
    })
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  onBluetoothDeviceFound() {

    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        console.log('device',device)
        device.name=device.name||device.localName
        if (device.name.indexOf('ZC1')>=0  ) {
          const foundDevices = this.data.devices
          const idx = inArray(foundDevices, 'deviceId', device.deviceId)
          const data = {}
          // let bf = device.advertisData.slice(2, 8);
          // console.log('bf', bf)
          // let mac = Array.prototype.map
          //   .call(new Uint8Array(bf), (x) => ("00" + x.toString(16)).slice(-2))
          //   .join(":");
          // mac = mac.toUpperCase();
          if (idx === -1) {

            data[`devices[${foundDevices.length}]`] = {
              ...device,
              // MAC: mac
            }
          } else {
            data[`devices[${idx}]`] = {
              ...device,
              // MAC: mac
            }
          }
          console.log(data)
          this.setData(data)
        }

      })
    })
  },
  createBLEConnection(e) {
    const that = this
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name =ds.name;
    this.stopBluetoothDevicesDiscovery()
    wx.request({
      url: `${config.prefix}/hydrants`,
      header: {
        Authorization: `Bearer ${app.globalData.userInfo.token}`
      },
      method: 'GET',
      data: {
        number: name.split("-")[1]
      },
      success: function (res) {
        if (res.statusCode === 200) {
          console.log('获取成功');
          if (res.data.data.length === 1) {
            wx.navigateTo({
              url: `/pages/detail/detail?deviceId=${deviceId}&name=${name}`
            })
          } else {
            console.log('系统中没有该设备')
            wx.showToast({
              title: '系统中没有该设备',
              icon: 'none'
            })
            wx.navigateTo({
              url: `/pages/detail/detail?deviceId=${deviceId}&name=${name}`
            })
            // util.toastError(`请先在系统中添加集中器${number}`)
          }
        } else {
          util.converErrorCodeToMsg(res)
        }

      }
    })

  },
  stopBluetoothDevicesDiscovery() {
    console.log('stopBluetoothDevicesDiscovery')
    wx.stopBluetoothDevicesDiscovery()
    this.setData({
      loading: false
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('list detail onUnload')
    this.stopBluetoothDevicesDiscovery()
    if (this.timer) {
      clearTimeout(this.timer)
    }
  },

})